package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @param
 * @return
 */
@WebServlet("/user/*")
public class UserServlet extends BeanServlet {
    //创建业务层对象复用
    public UserService service=new UserServiceImpl();
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用业务层方法
        List<User> list=service.findAll();
        //结果存进作用域，转发到页面
        req.setAttribute("list",list);
        System.out.println("list = " + list);
        req.getRequestDispatcher("/WEB-INF/pages/User_List.jsp").forward(req,resp);
    }
    public void addjsp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/User_Add.jsp").forward(req,resp);
    }
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取表单提交数据
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        //创建对象存储数据
        User user = new User(null, username, email);
        //调用业务层方法
        service.add(user);
        //调用查询方法
       findAll(req,resp);
    }
    public void updatejsp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
       req.setAttribute("updateId",Integer.parseInt(id));
        req.getRequestDispatcher("/WEB-INF/pages/User_Update.jsp").forward(req,resp);
    }
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取表单提交数据
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String id = req.getParameter("id");
        //创建对象存储数据
        User user = new User(Integer.parseInt(id), username, email);
        //调用业务层方法
        service.update(user);
        //调用查询方法
        findAll(req,resp);
    }
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //调用业务层方法
        service.delete(Integer.parseInt(id));
     findAll(req,resp);
    }
}
